package com.traffic.visim.log.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.traffic.visim.log.entity.ExceptionFlow;
import com.traffic.visim.log.entity.ExceptionIp;
import com.traffic.visim.log.entity.ExceptionPermission;
import com.traffic.visim.log.entity.PermissionIp;
import com.traffic.visim.log.mapper.ExceptionFlowMapper;
import com.traffic.visim.log.mapper.ExceptionIpMapper;
import com.traffic.visim.log.mapper.ExceptionPermissionMapper;
import com.traffic.visim.log.mapper.PermissionIpMapper;
import com.traffic.visim.log.service.LogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@Slf4j
public class LogServiceImpl implements LogService {
    @Autowired
    ExceptionIpMapper exceptionIpMapper;
    @Autowired
    ExceptionFlowMapper exceptionFlowMapper;
    @Autowired
    ExceptionPermissionMapper exceptionPermissionMapper;
    @Autowired
    PermissionIpMapper permissionIpMapper;

    @Override
    public void saveExceptionIp(ExceptionIp exceptionIp) {
        exceptionIpMapper.insert(exceptionIp);
    }

    @Override
    public void saveExceptionFlow(ExceptionFlow exceptionFlow) {
        exceptionFlowMapper.insert(exceptionFlow);
    }

    @Override
    public void saveExceptionPermission(ExceptionPermission exceptionPermission) {
        exceptionPermissionMapper.insert(exceptionPermission);
    }

    @Override
    public boolean findIp(String ip) {
        LambdaQueryWrapper<PermissionIp> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PermissionIp::getIp,ip).eq(PermissionIp::getState,0);
        PermissionIp permissionIp = permissionIpMapper.selectOne(queryWrapper);
        if (permissionIp == null){
            return false;
        }else {
            return true;
        }

    }

    @Override
    public long selectCountIp() {
        Date fiveTime = new Date(System.currentTimeMillis() - 5*60*1000);
        LambdaQueryWrapper<ExceptionIp> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ge(ExceptionIp::getCreateTime,fiveTime);
        return exceptionIpMapper.selectCount(queryWrapper);
    }

    @Override
    public long selectCountFlow() {
        Date fiveTime = new Date(System.currentTimeMillis() - 5*60*1000);
        LambdaQueryWrapper<ExceptionFlow> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ge(ExceptionFlow::getCreateTime,fiveTime);
        return exceptionFlowMapper.selectCount(queryWrapper);
    }

    @Override
    public long selectCountPermission() {
        Date fiveTime = new Date(System.currentTimeMillis() - 5*60*1000);
        LambdaQueryWrapper<ExceptionPermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ge(ExceptionPermission::getCreateTime,fiveTime);
        return exceptionPermissionMapper.selectCount(queryWrapper);
    }
}
